// CSE 142 Winter 2008, Marty Stepp // // This program reads an input file of data about students' attendance in // section and outputs the attendance, points earned, and grade percentages // for each student in each section. // // This second version breaks the program into methods for better structure // using arrays as parameters and returns. It also outputs to a file. import java.io.*; // for File, PrintStream import java.util.*; // for Scanner public class Sections2 { public static final int MAX_POINTS = 20; public static void main(String[] args) throws FileNotFoundException { PrintStream output = new PrintStream(new File("section_output.txt")); Scanner input = new Scanner(new File("sections.txt")); while (input.hasNextLine()) { // process a student String line = input.nextLine(); int[] students = computeAttended(line); int[] scores = computePoints(students); double[] percentages = computeGrades(scores); // to print to the console instead: // results(students, scores, percentages, System.out); results(students, scores, percentages, output); } } // Prints the overall output about a section. public static void results(int[] students, int[] scores, double[] percentages, PrintStream output) { output.println("Sections attended: " + Arrays.toString(students)); output.println("Student scores: " + Arrays.toString(scores)); output.println("Student grades: " + Arrays.toString(percentages)); output.println(); } // Reads the given line and computes each student's sections attended. public static int[] computeAttended(String line) { int[] students = new int[5]; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == '1') { // student went to class! // string "111111101011111101001110110110110001110010100" // index 01234567890123456789 // student 012340123401234 students[i % 5]++; } } // "chaining" - method A calls B, B calls C, C calls D, ... no returns // Chaining is bad because: // (a) main is not a good summary of the program // (b) the methods are forever linked; can't call them separately return students; } // Computes each student's points earned, based on the sections attended. public static int[] computePoints(int[] students) { int[] scores = new int[5]; for (int i = 0; i < students.length; i++) { scores[i] = Math.min(20, students[i] * 3); } return scores; } // Computes each student's grade, based on the points earned. public static double[] computeGrades(int[] scores) { double[] percentages = new double[5]; for (int i = 0; i < scores.length; i++) { percentages[i] = 100.0 * scores[i] / MAX_POINTS; } return percentages; } }